/**
 * 
 */
package biz.ritter.cobol.tool.convert.ds;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Bastie
 *
 */
public abstract class TreeToken extends DSToken {

	private ArrayList<DSToken> child = new ArrayList<DSToken>();
	private TreeToken parent;
	private String endToken;
	
	public void remove (DSToken child) {
		this.child.remove(child);
	}
	public void removeAll (List<DSToken> c) {
		this.child.removeAll(c);
	}
	
	public TreeToken(String token, TreeToken theParent) {
		super(token);
		this.parent = theParent;
	}
	
	public List<DSToken> childs() {
		return Collections.unmodifiableList(this.child);
	}
	
	public void replace (DSToken oldObject, DSToken newObject) {
		for (int i = 0; i < child.size();i++) {
			if (oldObject == child.get(i)){
				child.remove(i);
				child.add(i, newObject);
			}
		}
	}

	public void addChild (DSToken newChild) {
		this.child.add(newChild);
	}

	public TreeToken getParent () {
		return this.parent;
	}
	
	public boolean isRoot () {
		return null == this.parent;
	}
	public boolean isLeaf () {
		return 0 == this.child.size();
	}
	
	@Override
	public String toString() {
		StringBuilder result = new StringBuilder();
		result.append(this.getClass().getSimpleName()).append('[').append(this.getContent()).append(']').append(System.getProperty("line.separator"));
		for (DSToken nextChild : this.child) {
			TreeToken parent = this;
			do {
				result.append("  ");
			}
			while ((parent = parent.parent) != null);
			result.append(nextChild.toString()).append(System.getProperty("line.separator"));
		}
		return result.toString().trim();
	}

	public String getEndToken() {
		return null == endToken ? "" : endToken;
	}

	public void setEndToken(String endToken) {
		this.endToken = endToken;
	}
}
